import NProgress from '@/utils/nprogress' // progress
import { Router, RouteLocationNormalized } from 'vue-router'
import { useUserStore } from '@/store/user'
import { isLogin, getOauth, getCacheUserInfo } from '@/utils/auth'

const whiteList = ['/user/login', '/user/register']

function setupPageGuard(router: Router) {
  router.beforeEach(async (to: RouteLocationNormalized, _from, next) => {
    // start progress bar
    NProgress.start()

    // determine whether the user has logged in
    const hasToken = await isLogin()

    if (hasToken) {
      const userStore = useUserStore()
      if (!userStore.oauth.access_token) {
        const oauth = await getOauth()
        userStore.oauth = { ...oauth }
      }
      if (!userStore.currentUser.name) {
        const cacheUserInfo = await getCacheUserInfo()
        userStore.currentUser = { ...userStore.currentUser, ...cacheUserInfo }
      }
      if (to.path == '/user/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done()
      } else {
        next()
      }
    } else {
      /* has no token*/
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/user/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  })

  // 全局路由守卫 - atter
  router.afterEach((to) => {
    // 设置页面标题
    if (to.meta.title) {
      document.title = process.env.VUE_APP_TITLE
        ? `${to.meta.title} - ${process.env.VUE_APP_TITLE}`
        : (to.meta.title as string)
    }
    // 结束 progress bar 动画
    NProgress.done()
  })
}

export default function createRouteGuard(router: Router) {
  setupPageGuard(router)
}
